package com.hubu.parking.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hubu.parking.constant.ParkConstant;
import com.hubu.parking.entity.sys.SysConfig;
import com.hubu.parking.mapper.SysConfigMapper;
import com.hubu.parking.model.dto.park.ComputeCostDto;
import com.hubu.parking.model.dto.park.PageListConfigRequest;
import com.hubu.parking.service.SysConfigService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
* @author 19468
* @description 针对表【sys_config(系统全局配置表)】的数据库操作Service实现
* @createDate 2025-03-02 16:52:08
*/
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig>
    implements SysConfigService{

    @Override
    public Page<SysConfig> pageListConfigRecord(PageListConfigRequest pageRequest) {
        // 1.分页参数
        Page<SysConfig> page = new Page<>();
        page.setCurrent(pageRequest.getCurrent());
        page.setSize(pageRequest.getPageSize());
        // 2.查询条件
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        // 2.1 名字
        String name = pageRequest.getName();
        if (StrUtil.isNotBlank(name)) {
            queryWrapper.like(SysConfig::getName, name);
        }
        // 2.2 配置值
        String value = pageRequest.getValue();
        if (StrUtil.isNotBlank(value)) {
            queryWrapper.like(SysConfig::getValue, value);
        }
        // 2.3 描述
        String description = pageRequest.getDescription();
        if (StrUtil.isNotBlank(description)) {
            queryWrapper.like(SysConfig::getDescription, description);
        }
        // 3.取出用户姓名和车位编号设置进去
        return this.page(page, queryWrapper);
    }

    @Override
    public BigDecimal computeCost(ComputeCostDto dto) {
        long startTime = dto.getStartTime();
        long endTime = dto.getEndTime();
        SysConfig config = this.getByName(ParkConstant.COMPUTE_BASE_INTERVAL);
        int interval = Integer.parseInt(config.getValue());
        long percent = (endTime - startTime) / 1000 / 60 / interval;
        SysConfig costConfig = this.getByName(ParkConstant.COMPUTE_RATE_PER_UNIT);
        String ratePerUnit = costConfig.getValue();
        int unit = Integer.parseInt(ratePerUnit);
        return BigDecimal.valueOf((percent + 1) * unit);
    }

    @Override
    public SysConfig getByName(String name) {
        if (StrUtil.isBlank(name)) {
            return null;
        }
        LambdaQueryWrapper<SysConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysConfig::getName, name);
        return this.getOne(queryWrapper);
    }
}




